package com.gavindon.android.base

import android.app.Activity
import android.app.Application
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.widget.Button
import com.gavindon.android.BuildConfig
import com.gavindon.android.HomeActivity
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.FormatStrategy
import com.orhanobut.logger.Logger
import com.orhanobut.logger.PrettyFormatStrategy
import com.tencent.bugly.Bugly
import com.tencent.bugly.beta.Beta
import com.tencent.bugly.beta.UpgradeInfo
import com.tencent.bugly.beta.ui.UILifecycleListener
import java.util.*
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.gavindon.android.R
import com.gavindon.android.utils.SpUtils
import com.gavindon.android.widget.FocusViewUtils


/**
 * description:
 * Created by liNan on  2021/5/6 14:56
 */
class MyApplication : Application() {


    companion object {
        lateinit var appContext: Context
        private val activityStack = Stack<Activity>()
        fun getCurActivity(): Activity? {
            if (activityStack.empty()) return null
            return activityStack.lastElement()
        }

        fun removeAllActivity() {
            activityStack.forEach {
                it.finish()
            }
        }

        /*   fun initSmartRefresh() {
               SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout ->
                   layout.setPrimaryColorsId(R.color.window_bg)
                   ClassicsHeader(context)
               }
           }*/

    }

    override fun attachBaseContext(base: Context?) {
        //初始化tencent
        super.attachBaseContext(base)
//        initSmartRefresh()
//        MultiDex.install(base)
//        Beta.installTinker()
    }

    override fun onCreate() {
        super.onCreate()
        appContext = this
        initLogger()
        initBugly()
        SpUtils.init()
        registerActivityLifecycleCallbacks(activityLifecycleCallbacks)
    }


    private fun initLogger() {
        /*LOGGER初始化*/
        val formatStrategy: FormatStrategy = PrettyFormatStrategy.newBuilder()
            .showThreadInfo(BuildConfig.DEBUG)
            .tag("gavindon-logger") // (Optional) Global tag for every log. Default PRETTY_LOGGER
            .build()
        Logger.addLogAdapter(AndroidLogAdapter(formatStrategy))
    }

    private fun initBugly() {
        Beta.canShowUpgradeActs.add(HomeActivity::class.java)
        Beta.upgradeDialogLifecycleListener = object : UILifecycleListener<UpgradeInfo> {
            override fun onCreate(p0: Context?, view: View?, p2: UpgradeInfo?) {
                val confirmButton = view?.findViewWithTag<TextView>(Beta.TAG_CONFIRM_BUTTON)

                val cancelButton = view?.findViewWithTag<TextView>(Beta.TAG_CANCEL_BUTTON)
                confirmButton?.apply {
                    isFocusable = true
                    FocusViewUtils.scaleView(confirmButton, 0)
                }
                cancelButton?.apply {
                    isFocusable = true
                    FocusViewUtils.scaleView(cancelButton, 0)
                }
                view?.setOnKeyListener { v, keyCode, event ->
                    if (event.action == KeyEvent.ACTION_DOWN) {
                        if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
                            cancelButton?.requestFocus()
                            return@setOnKeyListener true
                        } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
                            confirmButton?.requestFocus()
                            return@setOnKeyListener true
                        }
                    }
                    return@setOnKeyListener false
                }

            }

            override fun onStart(p0: Context?, p1: View?, p2: UpgradeInfo?) {
            }

            override fun onResume(p0: Context?, p1: View?, p2: UpgradeInfo?) {
            }

            override fun onPause(p0: Context?, p1: View?, p2: UpgradeInfo?) {
            }

            override fun onStop(p0: Context?, p1: View?, p2: UpgradeInfo?) {
            }

            override fun onDestroy(p0: Context?, p1: View?, p2: UpgradeInfo?) {
            }

        }
        Bugly.init(this, "5a45bb6909", BuildConfig.DEBUG)
    }

/*    */
    /**
     * 兼容android P
     * 不同进程不可使用同一webView数据目录
     *//*
    private fun initWebView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val processName = getProcessName()
            if (packageName != processName) {
                android.webkit.WebView.setDataDirectorySuffix(processName)
            }
        }
        initX5()
    }

    private fun initX5() {
        //多进程优化
        val map = HashMap<String, Any>()
        map[TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER] = true
        map[TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE] = true
        QbSdk.initTbsSettings(map)
        QbSdk.initX5Environment(this, object : QbSdk.PreInitCallback {
            override fun onCoreInitFinished() {
            }

            override fun onViewInitFinished(p0: Boolean) {
            }
        })
    }*/


    private val activityLifecycleCallbacks = object : ActivityLifecycleCallbacks {
        override fun onActivityPaused(p0: Activity) {

        }

        override fun onActivityStarted(p0: Activity) {

        }

        override fun onActivityDestroyed(p0: Activity) {
            if (activityStack.contains(p0)) activityStack.remove(p0)
        }

        override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
        }

        override fun onActivityStopped(p0: Activity) {
            if (activityStack.contains(p0)) {
                activityStack.remove(p0)
                Logger.d("stoped--${activityStack.size}")
            }


        }

        override fun onActivityCreated(p0: Activity, p1: Bundle?) {
            if (!activityStack.contains(p0))
                activityStack.add(p0)
        }

        override fun onActivityResumed(p0: Activity) {
            if (!activityStack.contains(p0))
                activityStack.add(p0)
        }

    }

}